package org.acghub.mtdb.common;

import org.acghub.mtdb.util.ElementHelper;
import org.acghub.mtdb.util.StringUtil;
import org.w3c.dom.Element;

import java.util.Set;

/**
 * @author zhouhe
 */
public class Var extends Naming implements TypeDependency, VisitAcceptor, Meta {
    private String type;
    private String key;
    private String value;
    private String comment;
    private String defaultValue;
    private Type varType;

    // 反射调用
    public Var(Bean parent, Element self) throws Exception {
        super(parent, self);
    }

    @Override
    public void initialize(Element self) throws Exception {
        ElementHelper eh = new ElementHelper(self);
        Verify.verifyName(Verify.VerifyType.VAR, getName());
        this.type = eh.getString("type");
        this.key = eh.getString("key");
        this.value = eh.getString("value");
        this.comment = eh.getString("comment");
        this.defaultValue = eh.getString("default");
        if (this.type == null || this.type.isBlank()) {
            dump(System.err);
            throw new IllegalArgumentException("type is null");
        }
        eh.warnUnused("name");
    }

    @Override
    public boolean resolve() {
        varType = TypeFactory.resolve(this, type, key, value);
        if (varType == null) {
            return false;
        }
        if (StringUtil.isNotEmpty(defaultValue)) {
            varType.supportDefaultValue(defaultValue);
        }
        return true;
    }


    @Override
    public void depends(Set<Type> types) {
        varType.depends(types);
    }

    public Type getVarType() {
        return varType;
    }

    public String getComment() {
        return comment;
    }

    @Override
    public void accept(Visitor visitor) {
        this.varType.accept(visitor);
    }

    public String getDefaultValue() {
        return varType.getDefaultValue(value);
    }

    public String getType() {
        return type;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }
}
